package mutilthread;

/**
 * Created with IntelliJ IDEA.
 * Description: synchronized 用在方法上加锁
 * User: Li_yizYa
 * Date: 2025—03—21
 * Time: 18:37
 */
class Counter {
    public int count = 0;

    synchronized public void add() {
        count++;
    }
    //等价于上面的写法
//    public void add() {
//        synchronized (this) {
//            count++;
//        }
//    }
    //static 方法没有 this 的
    //static 方法也叫做“类方法”和具体的实例无关，知识和类相关
    //this是指向实例的
    //此时 static 方法和类对象相关，此时的写法就是给类对象加锁
    synchronized public static void func() {

    }
    //与上述写法等价
    public static void func2() {
        synchronized (Counter.class){

        }
    }
}
public class Demo6 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("counter = " + counter.count);
    }
}
